
#include "Relation.h"

#include <QXmlStreamReader>
#include <QXmlStreamWriter>
#include <QFile>

QList<Relation> Relation::GetRelations()
{
	QList<Relation> r;
	QFile f("xml/relations.xml");

	if(f.open(QIODevice::ReadOnly | QIODevice::Text))
	{
		QXmlStreamReader xml(&f);
		while(!xml.atEnd())
		{
			QXmlStreamReader::TokenType token = xml.readNext();

			if(token == QXmlStreamReader::StartDocument)
				continue;

			if(token == QXmlStreamReader::StartElement)
				r.append(ParseRelation(xml));
		}

		xml.clear();
		f.close();
	}
	return r;
}

Relation Relation::ParseRelation(QXmlStreamReader& xml)
{
	Relation r;

	xml.readNext();
	while(!(xml.tokenType() == QXmlStreamReader::EndElement && xml.name() == "relation"))
	{
		QXmlStreamReader::TokenType token = xml.readNext();

		if(token == QXmlStreamReader::EndElement)
			continue;

		if(xml.name() == "id1")
		{
			xml.readNext();
			r.SetId1(xml.text().toString().toInt());	
		}

		if(xml.name() == "id2")
		{
			xml.readNext();
			r.SetId2(xml.text().toString().toInt());
		}

		if(xml.name() == "bebe")
		{
			xml.readNext();
			r.AddBebe(xml.text().toString());	
		}

		if(xml.name() == "married")
		{
			xml.readNext();
			(xml.text().toString() == "true") ? r.SetMarried(true) : r.SetMarried(false);
		}
	}

	return r;
}

void Relation::SaveRelation(Relation r)
{
	QFile* file = new QFile("xml/relations.xml");
	QList<Relation> existingRelations = Relation::GetRelations();

	if(file->open(QIODevice::WriteOnly | QIODevice::Text))
	{
		QXmlStreamWriter *writer = new QXmlStreamWriter(file);
		writer->setAutoFormatting(true);
		writer->writeStartDocument();
		writer->writeStartElement("relations");
		
		for(int i=0; i<existingRelations.size(); i++)
			AddRelationXmlProperties(writer, existingRelations.at(i));

		AddRelationXmlProperties(writer, r);

		writer->writeEndElement();
		writer->writeEndDocument();
		file->close();
	}
}

void Relation::SaveRelations(QList<Relation> r)
{
	QFile* file = new QFile("xml/relations.xml");

	if(file->open(QIODevice::WriteOnly | QIODevice::Text))
	{
		QXmlStreamWriter *writer = new QXmlStreamWriter(file);
		writer->setAutoFormatting(true);
		writer->writeStartDocument();
		writer->writeStartElement("relations");
		
		for(int i=0; i<r.size(); i++)
			AddRelationXmlProperties(writer, r.at(i));

		writer->writeEndElement();
		writer->writeEndDocument();
		file->close();
	}
}

void Relation::AddRelationXmlProperties(QXmlStreamWriter* writer, Relation r)
{
	writer->writeStartElement("relation");
		
	writer->writeTextElement("id1", QString("%1").arg(r.GetId1()));
	writer->writeTextElement("id2", QString("%1").arg(r.GetId2()));
	
	(r.IsMarried()) ? writer->writeTextElement("married", QString("true")) 
		: writer->writeTextElement("married", QString("false"));

	for(int i=0; i<r.GetBebes().size(); i++)
		writer->writeTextElement("bebe", r.GetBebes().at(i));

	writer->writeEndElement();
}

